package cn.yunhe.action;

import cn.yunhe.util.BaseAction;
import lombok.Getter;
import lombok.Setter;
import org.apache.struts2.ServletActionContext;

import java.io.File;
import java.io.FileInputStream;

import java.io.FileOutputStream;

public class UpsAction extends BaseAction {
    @Getter
    @Setter
    private File[] uploads;

    @Getter
    @Setter
    private String[] uploadsFileName;

    @Getter
    @Setter
    private String[] uploadsContentType;

    @Setter
    private String savePath;

    @Override
    public String execute() throws Exception {
        String uploadsPath=getSavePath(savePath);
        for (int i = 0; i < uploads.length; i++) {
            doUpload(uploads[i],uploadsPath);
        }
        return SUCCESS;
    }

    private void doUpload(File file, String uploadsPath){
        try {
            FileOutputStream fos=new FileOutputStream(uploadsPath);
            FileInputStream fis=new FileInputStream(file);

            byte[] b=new byte[1024];
            int len=0;
            while ((len=fis.read(b))!=-1){
                fos.write(b,0,len);
            }

            fis.close();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String getSavePath(String path) {
        return ServletActionContext.getServletContext().getRealPath(path);
    }
}
